<template>
  <div>
    <div class="n-layout-page-header">
      <a-card :bordered="false" title="导出示例"> 可以选择导出格式 </a-card>
    </div>
    <a-card :bordered="false" class="mt-3 proCard">
      <BasicTable
        leftTitle="表格列表"
        leftTitleTooltip="这是一个提示"
        :columns="columns"
        :request="loadDataTable"
        row-key="id"
        ref="actionRef"
        :actionColumn="actionColumn"
        @update:checked-row-keys="onCheckedRow"
      >
        <template #toolbar>
          <a-button type="primary" @click="openModal">导出数据</a-button>
        </template>
      </BasicTable>
    </a-card>

    <basicModal @register="modalRegister" ref="modalRef" class="basicModal" @before-ok="okModal">
      <template #default>
        <BasicForm
          @register="register"
          @submit="handleSubmit"
          @reset="handleReset"
          class="basicForm"
        />
      </template>
    </basicModal>
  </div>
</template>

<script lang="ts" setup>
  import { reactive, unref, ref, h } from 'vue';
  import { BasicTable, TableAction } from '@/components/Table';
  import { basicModal, useModal } from '@/components/Modal';
  import { BasicForm, FormSchema, useForm } from '@/components/Form/index';
  import { getTableList } from '@/api/table/list';
  import { columns } from '../../comp/table/basicColumns';
  import { jsonToSheetXlsx } from '@/components/Excel';
  import { Message } from '@arco-design/web-vue';
  import { DeleteOutlined, FormOutlined } from '@vicons/antd';
  import { renderIcon } from '@/utils';

  const schemas: FormSchema[] = [
    {
      field: 'filename',
      component: 'Input',
      label: '文件名',
      labelMessage: '导出的文件以该名称命名',
      componentProps: {
        placeholder: '请输入文件名称',
        onInput: (e: any) => {
          console.log(e);
        },
      },
      rules: [{ required: true, message: '请输入导出的文件名称', trigger: ['blur'] }],
    },
    {
      field: 'bookType',
      component: 'Select',
      label: '文件类型',
      componentProps: {
        placeholder: '请选择文件类型',
        options: [
          {
            label: 'xlsx',
            value: 'xlsx',
          },
          {
            label: 'html',
            value: 'html',
          },
          {
            label: 'csv',
            value: 'csv',
          },
          {
            label: 'txt',
            value: 'txt',
          },
        ],
        onChange: (e: any) => {
          console.log(e);
        },
      },
      rules: [{ required: true, message: '请选择文件类型', trigger: ['change'] }],
    },
  ];

  const actionRef = ref();
  const modalRef = ref();
  const tableData = ref();

  const params = reactive({
    pageSize: 5,
    name: 'xiaoMa',
  });

  const [modalRegister, { openModal }] = useModal({
    title: '导出数据',
  });

  const [register, { submit }] = useForm({
    // submitButtonText: '提交预约',
    showActionButtonGroup: false,
    schemas,
  });

  const actionColumn = reactive({
    width: 160,
    title: '操作',
    key: 'action',
    fixed: 'right',
    align: 'center',
    render({ record }) {
      return h(TableAction as any, {
        style: 'button',
        actions: [
          {
            label: '删除',
            type: 'primary',
            status: 'danger',
            icon: renderIcon(DeleteOutlined),
            popConfirm: {
              content: '您真的，确定要删除吗？',
              okText: '确定',
              cancelText: '取消',
              onOk: handleDelete.bind(null, record),
            },
          },
          {
            label: '编辑',
            type: 'primary',
            icon: renderIcon(FormOutlined),
            popConfirm: {
              content: '您真的，确定要编辑吗？',
              okText: '确定',
              cancelText: '取消',
              onOk: handleEdit.bind(null, record),
            },
          },
        ],
      });
    },
  });

  async function okModal() {
    const formRes = await submit();
    if (formRes) {
      modalRef.value.closeModal();
      Message.success('提交成功');
      return true;
    } else {
      Message.error('验证失败，请填写完整信息');
      modalRef.value.setSubLoading(false);
    }
  }

  function handleReset(values: Recordable) {
    console.log(values);
  }

  const loadDataTable = async (res) => {
    const result = await getTableList({ ...params, ...res });
    tableData.value = result.list;
    return result;
  };

  function onCheckedRow(rowKeys) {
    console.log(rowKeys);
  }

  function handleDelete(record) {
    console.log(record);
    Message.success(`删除${record.name}，成功`);
  }

  function handleEdit(record) {
    console.log(record);
    Message.success('您点击了编辑按钮');
  }

  function handleSubmit(values: Recordable) {
    console.log(values);
    // 默认Object.keys(data[0])作为header
    const { filename, bookType } = values;
    jsonToSheetXlsx({
      data: unref(tableData),
      filename: `${filename.split('.').shift()}.${bookType}`,
      write2excelOpts: {
        bookType,
      },
    });
    Message.success(JSON.stringify(values));
  }
</script>

<style lang="less" scoped></style>
